

package com.wlstock.funi.ui;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.em.baselistener.OnBackListener;
import com.em.baselistener.OnMoreListener;
import com.em.baselistener.OnTitleClickListener;
import com.em.widget.view.SelectPopUpWindow;
import com.em.widget.view.SelectPopUpWindow.onPopViewListener;
import com.wlstock.funi.R;
import com.wlstock.funi.adapter.SelfFundAdapter;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.dao.MyAccountStockDao;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.dao.SelfFundSetDao;
import com.wlstock.funi.dao.SelfFundTagDao;
import com.wlstock.funi.dao.StockBaseInfoDao;
import com.wlstock.funi.dao.StrategyFundSelDao;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.model.SelfFundSetModel;
import com.wlstock.funi.model.SelfFundTagModel;
import com.wlstock.funi.model.StrategyFundModel;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.service.LatestPriceService;
import com.wlstock.funi.service.LatestPriceService.LatestPriceServiceBinder;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.IntentContants;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.ToastUtils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelfFundActivity extends FundBaseFragmentActivity implements NetWorkListener, TaskLitener<String, List<SelfFundModel>>, TaskResultListener<List<SelfFundModel>>, OnClickListener, OnItemLongClickListener, OnItemClickListener, OnMoreListener, onPopViewListener, OnBackListener, SelectPopUpWindow.onDeleteViewListener, OnTitleClickListener, QuickSet.okListener {
	private LatestPriceServiceBinder binder;
	private List<SelfFundModel> allSelfFundModels;
	private ListView lv_self_fund;
	private SelfFundAdapter fundAdapter;
	private EditText ed_stkcode;
	private EditText ed_stkname;
	private Button btn_add;
	
	private boolean isBindService = false;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_selffund);
		setTitle(getString(R.string.title_selffund));
		showMoreBtn(this);
		onBackClick(this);
		onTitleClick(this);
		
		lv_self_fund = (ListView) findViewById(R.id.lv_self_fund);
		
		ed_stkcode = (EditText) findViewById(R.id.ed_stkcode);
		ed_stkname = (EditText) findViewById(R.id.ed_stkname);
		btn_add = (Button) findViewById(R.id.btn_add);
		btn_add.setOnClickListener(this);
		ed_stkcode.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence text, int arg1, int arg2, int arg3) {
				if (text.toString().isEmpty() || text.toString() == null) {
					getAll();
					return;
				}
				
				List<SelfFundModel> sfSearchModels = SelfFundDao.getInstance(SelfFundActivity.this).querySelfFundModelsLike(text.toString());
				if (sfSearchModels!=null && sfSearchModels.size() > 0) {
					updateDetectList(sfSearchModels);
				}else {
					String stkName = StockBaseInfoDao.getInstance(SelfFundActivity.this).queryName(text.toString());
					ed_stkname.setText(stkName);	
				}
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});
		getAll();
		lv_self_fund.setOnItemLongClickListener(this);
		lv_self_fund.setOnItemClickListener(this);	
	}
	
	private void getAll() {
		List<SelfFundModel> daoList = SelfFundDao.getInstance(SelfFundActivity.this).queryAllSelfFundModes();
		updateDetectList(daoList);
	}

	private void updateDetectList(List<SelfFundModel> daoList) {
		allSelfFundModels = new ArrayList<SelfFundModel>(daoList);

		if (allSelfFundModels!=null) {
			fundAdapter = new SelfFundAdapter(this,allSelfFundModels);
			lv_self_fund.setAdapter(fundAdapter);
			if (binder!=null && binder.getService()!=null){
				binder.getService().setFundModels(SelfFundActivity.this.allSelfFundModels);
			}
		}
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
//		EventBus.getDefault().unregister(this);
		if (isBindService) {
			binder.getService().setNetWorkListener(null);
			binder.getService().setFundModels(null);
			unbindService(connection);	
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		Intent intent = new Intent(this, LatestPriceService.class);
		isBindService =  bindService(intent, connection, BIND_AUTO_CREATE);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	private ServiceConnection connection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			// TODO Auto-generated method stub
			binder.getService().setNetWorkListener(null);
			binder.getService().setFundModels(null);
		}
		
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder binder) {
			// TODO Auto-generated method stub
			SelfFundActivity.this.binder = (LatestPriceServiceBinder) binder;
			SelfFundActivity.this.binder.getService().setNetWorkListener(SelfFundActivity.this);
			SelfFundActivity.this.binder.getService().setFundModels(SelfFundActivity.this.allSelfFundModels);
		}
	};

	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		if (eventCode == EventBusConstants.EVENT_STOCKS_UPDATE_MUTI_PRICE) {
			
		}
	}

	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		if (eventCode == EventBusConstants.EVENT_STOCKS_UPDATE_MUTI_PRICE) {
			FundAsyTask<String, Void, List<SelfFundModel>> task = new FundAsyTask<String, Void, List<SelfFundModel>>();
			task.backListener = this;
			task.resultListener = this;
			task.execute(response);
		}
	}

	@Override
	public void onResponse(String response, String eventCode) {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	public void onPostResult(List<SelfFundModel> result) {
		// TODO Auto-generated method stub
		ToastUtils.showMiddleMsg(this, "Update Price Successs");
		allSelfFundModels = result;
		fundAdapter.notifyDataSetChanged();
	}

	@Override
	public List<SelfFundModel> doInBackground(String... params) {
		// TODO Auto-generated method stub
		return SelfFundDao.getInstance(this).parseSinaMultiPrices(params[0], allSelfFundModels);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_add:
			if (StockUtils.isStkValid(ed_stkcode.getText().toString())) {
				final String[] tagNames = SelfFundTagDao.getInstance(this).queryAllTagNames();
				final SelfFundModel mode = new SelfFundModel();
				mode.setStockNo(ed_stkcode.getText().toString());
				mode.setStockName(ed_stkname.getText().toString());
				mode.setSourceCode(SelfFundModel.SOURCE_CUSTOMADD);

				if (tagNames!=null) {
					new AlertDialog.Builder(this).setTitle("选择标签").setItems(tagNames, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int which) {
							mode.setTag(tagNames[which]);
							SelfFundDao.getInstance(SelfFundActivity.this).addOrUpdateSelfModel(mode);
							updateList(mode);
							ToastUtils.showMiddleMsg(SelfFundActivity.this, "新增成功");
							}
					}).setNegativeButton("取消",null).show();
				}else {
					mode.setTag(SelfFundModel.TAG_DEFAULT);
					SelfFundDao.getInstance(this).addOrUpdateSelfModel(ed_stkcode.getText().toString(),ed_stkname.getText().toString(),SelfFundModel.TAG_DEFAULT);
					updateList(mode);
					ToastUtils.showMiddleMsg(SelfFundActivity.this, "新增成功");
				}
				ed_stkcode.setText("");
				ed_stkname.setText("");
			}else {
				ToastUtils.showMiddleMsg(this, "代码错误");
			}
			break;
		default:
			break;
		}
	}

	private void updateList(SelfFundModel mode) {
		// TODO 更新数据
		if (allSelfFundModels!=null) {
			allSelfFundModels.add(mode);
			fundAdapter.setModels(allSelfFundModels);
			fundAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int idx,
			long arg3) {
		final SelfFundModel selectMode = allSelfFundModels.get(idx);
		new AlertDialog.Builder(this).setTitle("是否删除").setMessage("删除"+selectMode.getStockName()+"?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				SelfFundDao.getInstance(SelfFundActivity.this).deleteWithStkNo(selectMode.getStockNo());
				binder.getService().getNewlyFundModels();
				allSelfFundModels.remove(selectMode);
				fundAdapter.notifyDataSetChanged();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		}).create().show();
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int idx, long arg3) {
		SelfFundModel tmpModel = allSelfFundModels.get(idx);
		Intent intent = new Intent(SelfFundActivity.this, SelfFundSetActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(IntentContants.INTENT_STKCODE, tmpModel.getStockNo());
		bundle.putString(IntentContants.INTENT_STKNAME, tmpModel.getStockName());
		bundle.putString(IntentContants.INTENT_CUR_PRICE, String.valueOf(tmpModel.getCurPrice()));
		bundle.putString(IntentContants.INTENT_HIGH_PRICE, String.valueOf(tmpModel.gethPrice()));
		bundle.putString(IntentContants.INTENT_LOW_PRICE, String.valueOf(tmpModel.getLowPrice()));
		bundle.putString(IntentContants.INTENT_OPEN_PRICE, String.valueOf(tmpModel.getCurOpen()));
		bundle.putString(IntentContants.INTENT_LAST_CLOSE, String.valueOf(tmpModel.getlastClose()));
		MyAccountStocks ownStock = MyAccountStockDao.getInstance(this).queryStock(tmpModel.getStockNo());
		if (ownStock != null) {
			bundle.putInt(IntentContants.INTENT_MODE, IntentContants.INTENT_MODE_SAILE);
		} else {
			bundle.putInt(IntentContants.INTENT_MODE, IntentContants.INTENT_MODE_BUY);
		}
		intent.putExtras(bundle);
		startActivity(intent);
	}

	@Override
	public void onMoreClick(View v) {
		// TODO Auto-generated method stub
		showPopUpView(getMenuList(), this,this);
	}

	private List<Map<String, Object>> getMenuList() {
		// TODO Auto-generated method stub'
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();		
		map.put("name", getResources().getString(R.string.pop_title_wanglong));
		map.put("isEdit","Y");
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_own));
		map.put("isEdit","Y");
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_market));
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_strategy_fundmodel));
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_custom_add));
		list.add(map);
		
		List<SelfFundTagModel> tags = SelfFundTagDao.getInstance(SelfFundActivity.this).queryAllTags();
		if (tags != null && tags.size()>0) {
			for(SelfFundTagModel item : tags){
				map = new HashMap<String, Object>();
				map.put("name", item.getTag());
				map.put("isEdit","Y");
				map.put("tag",item.getTag());
				list.add(map);
			}
		}

		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_add_sf_group));
		list.add(map);
		
		return list;
	}

	@Override
	public void onViewSelectListener(String str) {
		
		List<SelfFundModel> tmpList = new ArrayList<SelfFundModel>();
		if (str.equals(getResources().getString(R.string.pop_title_all))) {
			tmpList = SelfFundDao.getInstance(this).queryAllSelfFundModes();
		}else if (str.equals(getResources().getString(R.string.pop_title_custom_add))) {
			tmpList = SelfFundDao.getInstance(this).queryFundModelsWithType(SelfFundModel.SOURCE_CUSTOMADD);
		}else if (str.equals(getResources().getString(R.string.pop_title_wanglong))) {
			tmpList = SelfFundDao.getInstance(this).queryFundModelsWithType(SelfFundModel.SOURCE_WANGLONG);
		}else if (str.equals(getResources().getString(R.string.pop_title_own))) {
			ArrayList<MyAccountStocks> ownStocks = MyAccountStockDao.getInstance(this).queryAccountStocks();
			if (ownStocks!=null) {
				for (int i = 0; i < ownStocks.size(); i++) {
					SelfFundModel sfModel = new SelfFundModel();
					sfModel.setMyStock(ownStocks.get(i));
					tmpList.add(sfModel);
				}	
			}
		}else if (str.equals(getResources().getString(R.string.pop_title_market))) {
			tmpList = SelfFundDao.getInstance(this).queryFundModelsWithType(SelfFundModel.SOURCE_ZB);
		}else if (str.equals(getResources().getString(R.string.pop_title_strategy_fundmodel))){
			List<StrategyFundModel> strategyFundModels =StrategyFundSelDao.getInstance(this).queryStraByOffsetDays(new Date(),-10);

			for (StrategyFundModel model : strategyFundModels){
				SelfFundModel selfFundModel = new SelfFundModel(model);
				tmpList.add(selfFundModel);
			}
		}
		else if (str.equals(getResources().getString(R.string.pop_title_add_sf_group))) {
			//增加标签
			final EditText ed = new EditText(this);
			new AlertDialog.Builder(this).setView(ed).setTitle("增加标签").setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					ToastUtils.showMiddleMsg(SelfFundActivity.this, ed.getText().toString());
					SelfFundTagModel tagModel = new SelfFundTagModel();
					tagModel.setTag(ed.getText().toString());
					SelfFundTagDao.getInstance(SelfFundActivity.this).createOrUpdate(tagModel);
					invalidPopView(getMenuList());
				}
			}).show();
		}else{
			//标签中的
			tmpList = SelfFundDao.getInstance(this).queryFundModelsWithTag(str);
		}
			
		if (tmpList!=null) {
			updateDetectList(tmpList);
			setTitle(str+"("+tmpList.size()+"条)");
		}else{
			setTitle(str+"(0条)");
		}
	}

	@Override
	public void onBackClick(View v) {
		// TODO Auto-generated method stub
		this.finish();
	}

	@Override
	public void onDelete(View v) {
		String str = (String) v.getTag();
		if (str.equals(getResources().getString(R.string.pop_title_wanglong))){
			SelfFundDao.getInstance(this).deleteWithSourceCode(SelfFundModel.SOURCE_WANGLONG);
		}else {
			SelfFundTagDao.getInstance(this).deleteWithTagName(str);
		}
		invalidPopView(getMenuList());
	}

	@Override
	public void onTitleClick(View v) {
		final QuickSet quickSetVeiw = new QuickSet(this);
		quickSetVeiw.okListener = SelfFundActivity.this;
		new AlertDialog.Builder(this).setView(quickSetVeiw).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				new AlertDialog.Builder(SelfFundActivity.this).setTitle("确定执行操作?").setMessage("是否执行批量保存设置操作?本次操作共"+allSelfFundModels.size()+"条").setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							quickSetVeiw.getValue();
						} catch (ParseException e) {
							onError();
						}
					}
				}).setNegativeButton("取消",null).show();
			}
		}).setNegativeButton("取消",null).show();
	}

	@Override
	public void onOK(float specifiPrice, long totalPrice, Date beginDate, Date endDate, String beginTime, String endTime, boolean isQuickBuy) {

	}

	@Override
	public void onOK(int type, float offset, long totalPrice, Date beginDate, Date endDate, String beginTime, String endTime, boolean isQuickBuy) {
		ArrayList<SelfFundSetModel> sfSetModels = new ArrayList<SelfFundSetModel>();
		for (int i = 0 ; i < allSelfFundModels.size(); i++){
			SelfFundModel sfModel = allSelfFundModels.get(i);
			SelfFundSetModel sfSetModel = new SelfFundSetModel();
			sfSetModel.setStkNo(sfModel.getStockNo());
			sfSetModel.setStkName(sfModel.getStockName());
			sfSetModel.setStartDay(beginDate);
			sfSetModel.setEndDay(endDate);
			sfSetModel.setStartTime(beginTime);
			sfSetModel.setEndTime(endTime);
			sfSetModel.setPending(SelfFundSetModel.PENDING);
			sfSetModel.setTradeType(OperateModel.TradeType_BUY);
			sfSetModel.setTotalMoney(totalPrice);
			sfSetModel.setPrice(getPrice(type,sfModel,offset));
			sfSetModel.setQuickBuy(true);
			sfSetModel.setCreateDate(new Date());
			sfSetModels.add(sfSetModel);
		}

		if (sfSetModels!=null && sfSetModels.size()>0){
			SelfFundSetDao.getInstance(this).addOrUpdateList(sfSetModels);
		}
	}

	private float getPrice(int type, SelfFundModel sfModel, float offset) {
		float price = 0.f;
		if (type == QuickSet.TYPE_OPEN){
			price = sfModel.getCurOpen();
		}else if (type == QuickSet.TYPE_CLOSE){
			price = sfModel.getlastClose();
		}else if (type == QuickSet.TYPE_HIGH){
			price = sfModel.gethPrice();
		}else if (type == QuickSet.TYPE_LOW){
			price = sfModel.getLowPrice();
		}else if (type == QuickSet.TYPE_CUR){
			price = sfModel.getCurPrice();
		}

		return CaculateUtils.getBuyPrice(price,offset);
	}

	@Override
	public void onError() {
		ToastUtils.showMiddleMsg(this,"格式不正确");
	}
}
